<?php

class WxPayment {

    function get_payform($order_info) {

        $order_info = $this->get_order_info($order_info);

        define("APPID", C('app_wx_appid'));
        define("MCHID", C('app_wx_mchid'));
        define("KEY", C('app_wx_key'));
        define("APPSECRET", C('app_wx_appsecret'));

        import('Mall.Payment.Wxpay.WxPayApi', '', '.php');
        //统一下单  nonce_str、sign、spbill_create_ip  在接口调用统一设置
        $input = new \WxPayUnifiedOrder();
        $input->SetBody($order_info['order_sn']);
        $input->SetAttach($order_info['order_id']);
        $input->SetOut_trade_no($order_info['order_sn']);
        $input->SetTotal_fee(intval(bcmul($order_info['money'], 100, 0)));
        $input->SetNotify_url('http://www.jingjing.shop/notifywx.php'); //
        $input->SetTrade_type('APP');

        $wxpay = new \WxPayApi();
        $order = $wxpay->unifiedOrder($input);



//        echo date('Y-m-d H:i:s',  time());
        if ($order['return_code'] == 'SUCCESS') {
            if ($order['result_code'] == 'SUCCESS') {
                $order['timestamp'] = time();
                $order['sign'] = $this->sign_again($order);
                render('10000', '', array('response' => $order));
            } else {
                render('19999', '', array('response' => $order));
            }
        } else {
            render('19999', '', array('response' => $order));
        }
    }

    function sign_again($order) {
        $values['appid'] = APPID;
        $values['partnerid'] = MCHID;
        $values['prepayid'] = $order['prepay_id'];
        $values['package'] = 'Sign=WXpay';
        $values['noncestr'] = $order['nonce_str'];
        $values['timestamp'] = $order['timestamp'];
        
        ksort($values);
        $buff = "";
        foreach ($values as $key => $value) {
            $buff .= $key . "=" . $value . "&";
        }

        $string = trim($buff, "&");
        $string = $string . "&key=" . KEY;
        $string = md5($string);
        //签名步骤四：所有字符转为大写
        $result = strtoupper($string);
        return $result;
    }


    function verify_notify() {
        define("APPID", C('app_wx_appid'));
        define("MCHID", C('app_wx_mchid'));
        define("KEY", C('app_wx_key'));
        define("APPSECRET", C('app_wx_appsecret'));

        import('Mall.Payment.Wxpay.WxPayApi', '', '.php');
        import('Mall.Payment.Wxpay.WxPayNotify', '', '.php');

        $notify = new \WxPayNotify();
        $notify->Handle(false);
        $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
        $data = $notify->FromXml($xml);
//        $data = unserialize('a:17:{s:5:"appid";s:18:"wx65ea6cb402565257";s:6:"attach";s:10:"1491293185";s:9:"bank_type";s:10:"CMB_CREDIT";s:8:"cash_fee";s:1:"1";s:8:"fee_type";s:3:"CNY";s:12:"is_subscribe";s:1:"N";s:6:"mch_id";s:10:"1451261902";s:9:"nonce_str";s:32:"ritkibas1i8py3qatdt275kzbvj5nft7";s:6:"openid";s:28:"o3kLx0rwsQVbobTG5KoiRXKFpHtQ";s:12:"out_trade_no";s:10:"1491293185";s:11:"result_code";s:7:"SUCCESS";s:11:"return_code";s:7:"SUCCESS";s:4:"sign";s:32:"CA8CD53E20EE5FFE3F58B6372CE1D74D";s:8:"time_end";s:14:"20170404160702";s:9:"total_fee";s:1:"1";s:10:"trade_type";s:3:"APP";s:14:"transaction_id";s:28:"4001522001201704045834278811";}');

        if (!array_key_exists("transaction_id", $data)) {
            $verify_notify = false;
        } else {
            $transaction_id = $data['transaction_id'];
            $input = new \WxPayOrderQuery();
            $input->SetTransaction_id($transaction_id);
            $wxpay = new \WxPayApi();
            $result = $wxpay->orderQuery($input);
            if (array_key_exists("return_code", $result) && array_key_exists("result_code", $result) && $result["return_code"] == "SUCCESS" && $result["result_code"] == "SUCCESS") {
                $verify_notify = TRUE;
            } else {
                $verify_notify = false;
            }
        }
        if ($verify_notify) {
            $notify_result = array(
                'out_trade_no' => $data["out_trade_no"], #商户订单号
                'trade_no' => $data['transaction_id'], #交易凭据单号
                'total_fee' => $data["total_fee"] / 100, #涉及金额
                'trade_status' => '1',
            );
        } else {
            $notify_result = array(
                'trade_status' => '0',
            );
        }
        return $notify_result;
    }

    function get_order_info($order_info) {
        if ($order_info['is_order_array']) {
            $order_info0 = $order_info;
            $order_info = array();
            foreach ($order_info0['item'] as $fe_order_info) {
                if (!$order_info['money']) {
                    $order_info['money'] = bcsub($fe_order_info['order_amount'], $fe_order_info['pd_amount'], 2);
                } else {
                    $order_info['money'] = bcadd($order_info['money'], bcsub($fe_order_info['order_amount'], $fe_order_info['pd_amount'], 2), 2);
                }

                if (!($new_order_sn)) {
                    $new_order_sn = $fe_order_info['order_sn'];
                    $out_trade_no = $new_order_sn;
                    $orders_group = $fe_order_info['order_id'];
                    $order_info['buyer_id'] = $fe_order_info['buyer_id'];
                    $order_info['payment_name'] = $fe_order_info['payment_name'];
                    $order_info['buyer_name'] = $fe_order_info['buyer_name'];
                    $order_info['order_sn'] = $new_order_sn;
                    $order_info['order_id'] = $fe_order_info['order_id'];
                } else {
                    $orders_group.=',' . $fe_order_info['order_id'];
                }
            }
            $account_log_mod = M('account_log');
            $account_log = array(
                'user_id' => $order_info['buyer_id'],
                'user_name' => $order_info['buyer_name'],
                'order_sn' => $new_order_sn,
                'orders_group' => $orders_group,
                'add_time' => time(),
                'type' => ACCOUNT_TYPE_CZ,
                'money_flow' => 'income',
                'money' => $order_info['money'],
                'log_text' => $order_info['buyer_name'] . "充值" . $order_info['money'] . "元(" . $order_info['payment_name'] . ")",
            );
            $account_log_mod->add($account_log);
        } else {
            $order_info['money'] = bcsub($order_info['order_amount'], $order_info['pd_amount'], 2);
            $order_info = $this->add_account_log($order_info);
            if (!$order_info) {
                return false;
            }
        }
        return $order_info;
    }

    function add_account_log($order_info) {
        $account_log_mod = M('account_log');
        $account_log = $account_log_mod->where('order_sn=' . $order_info['order_sn'])->find();
        if (empty($account_log)) {
            $account_log = array(
                'user_id' => $order_info['buyer_id'],
                'order_id' => $order_info['order_id'],
                'user_name' => $order_info['buyer_name'],
                'order_sn' => $order_info['order_sn'],
                'add_time' => time(),
                'type' => ACCOUNT_TYPE_CZ,
                'money_flow' => 'income',
                'money' => $order_info['money'],
                'log_text' => $order_info['buyer_name'] . "充值" . $order_info['money'] . "元(" . $order_info['payment_name'] . ")",
            );
            $account_log_mod->add($account_log);
        } else {
            if ($account_log['complete'] == 1) {
                return false;
            }
            //如果更换支付方式，记录需发生变化。
            $data['log_text'] = $order_info['buyer_name'] . "充值" . $order_info['money'] . "元(" . $order_info['payment_name'] . ")";
            if ($account_log['money'] != $order_info['money']) {
                //订单金额发生改变会导致不允许支付，需要更换订单号
                $new_order_sn = D('Order')->_gen_order_sn();
                //金额不一致需修改。
                $data['money'] = $order_info['money'];
                $data['order_sn'] = $new_order_sn;
                //修改订单order_sn
                $order_mod = & m('order');
                $order_mod->where('order_id=' . $order_info['order_id'])->save(array('order_sn' => $new_order_sn));
                $order_info['order_sn'] = $new_order_sn;
            }
            $account_log_mod->where('id=' . $account_log['id'])->save($data);
        }
        return $order_info;
    }

}
